<template>
  <div class="admin-bg">
    <div class="admin-container">
      <header class="app-header">
        <div class="nav-container">
          <div class="logo-title">
            <img :src="require('@/assets/picture/0.jpg')" alt="系统Logo" class="logo" />
            <div class="system-title">DLNU奖学金管理系统</div>
          </div>
          <nav>
            <ul>
              <li><router-link to="/fst">首页</router-link></li>
              <li><router-link to="/announcement">公告通知</router-link></li>
              <li><a href="/awards.pdf" target="_blank">评选制度</a></li>
              <li><span>获奖名单</span></li>
            </ul>
          </nav>
        </div>
      </header>

     
      <main class="main-area">
        <h2 class="page-title">学生信息管理</h2>

      
        <div class="filter-row">
          <el-select v-model="filters.college" placeholder="学院" clearable style="width: 150px" @change="filterData">
            <el-option v-for="item in colleges" :key="item" :label="item" :value="item" />
          </el-select>
          <el-select v-model="filters.department" placeholder="专业" clearable style="width: 150px" @change="filterData">
            <el-option v-for="item in departments" :key="item" :label="item" :value="item" />
          </el-select>
          <el-select v-model="filters.grade" placeholder="年级" clearable style="width: 150px" @change="filterData">
            <el-option label="研一" value="1" />
            <el-option label="研二" value="2" />
            <el-option label="研三" value="3" />
          </el-select>
          <el-input v-model="searchStudentId" placeholder="按学号查找" style="width: 200px" @input="filterData" clearable />
        </div>

      
        <div class="module-buttons" style="margin: 20px 0; text-align: center;">
          <el-button
            v-for="mod in modules"
            :key="mod.key"
            :type="currentModule?.key === mod.key ? 'primary' : 'default'"
            :disabled="!selectedStudent"
            style="margin: 5px; min-width: 120px;"
            @click="openModule(mod.key)"
          >
            {{ mod.label }}
          </el-button>
        </div>

      
        <el-table 
          :data="filteredStudents" 
          border 
          style="margin-top: 20px"
          @current-change="handleStudentSelect"
          highlight-current-row
        >
          <el-table-column prop="studentId" label="学号" width="150" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="college" label="学院" width="150" />
          <el-table-column prop="department" label="专业" width="150" />
          <el-table-column prop="gradeYear" label="年级" width="100">
            <template #default="scope">
              {{ scope.row.gradeYear === 1 ? '研一' : scope.row.gradeYear === 2 ? '研二' : '研三' }}
            </template>
          </el-table-column>
          <el-table-column prop="hasApplied" label="是否申请" width="120">
            <template #default="scope">
              {{ scope.row.hasApplied ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column prop="evaluationResult" label="评判结果" width="150" />
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button size="small" type="danger" @click="deleteStudent(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        
        <div v-show="shouldShowModule" style="margin-top: 20px; padding: 20px; background: white; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3>{{ currentModule?.label }} - {{ currentStudent?.name }}</h3>
            <el-button @click="closeCurrentModule">关闭</el-button>
          </div>
          
          <component
            v-if="shouldShowModule"
            :is="currentModule.component"
            :key="`${currentModule.key}-${currentStudentId}-${componentKey}`"
            :studentId="currentStudentId"
            @close="closeCurrentModule"
            @save-success="handleSaveSuccess"
          />
        </div>
      </main>
    </div>
  </div>
</template>

<script>
import AcademicScoresModule from './Modules/AcademicScoresModule.vue'
import ResearchOutputsModule from './Modules/ResearchOutputsModule.vue'
import MoralScoresModule from './Modules/MoralScoresModule.vue'
import CompetitionsModule from './Modules/CompetitionsModule.vue'
import ResearchProjectsModule from './Modules/ResearchProjectsModule.vue'
import SocialServicesModule from './Modules/SocialServicesModule.vue'
import ScholarshipApplicationsModule from './Modules/ScholarshipApplicationsModule.vue'
import axios from 'axios'
import { markRaw } from 'vue'

export default {
  name: 'UserHome',
  data() {
    return {
      students: [],
      filteredStudents: [],
      currentStudent: null,
      selectedStudent: null,
      currentModule: null,
      componentKey: 0,
      filters: { college: '', department: '', grade: '' },
      searchStudentId: '',
      colleges: [],
      departments: [],
      modules: [
        { key: 'academic', label: '学业成绩', component: markRaw(AcademicScoresModule) },
        { key: 'researchOutputs', label: '科研成果', component: markRaw(ResearchOutputsModule) },
        { key: 'moralScores', label: '思政评分', component: markRaw(MoralScoresModule) },
        { key: 'competitions', label: '竞赛成绩', component: markRaw(CompetitionsModule) },
        { key: 'researchProjects', label: '科研项目', component: markRaw(ResearchProjectsModule) },
        { key: 'socialServices', label: '社会服务', component: markRaw(SocialServicesModule) },
        { key: 'scholarshipApplications', label: '奖学金申请', component: markRaw(ScholarshipApplicationsModule) }
      ]
    }
  },
  computed: {
    shouldShowModule() {
      return this.currentStudent && this.currentModule
    },
    currentStudentId() {
      return this.currentStudent?.studentId
    }
  },
  created() {
    this.loadStudentData()
  },
  methods: {
    async loadStudentData() {
      try {
        const [studentsRes, appsRes] = await Promise.all([
          axios.get('/api/students/all'),
          axios.get('/api/scholarshipapplications/all')
        ])
        
        const appMap = new Map((appsRes.data || []).map(app => [app.studentId, app]))
        this.students = (studentsRes.data || []).map(s => ({
          ...s,
          hasApplied: !!appMap.get(s.studentId),
          evaluationResult: appMap.get(s.studentId)?.result || '未申请'
        }))
        
        this.colleges = [...new Set(this.students.map(s => s.college).filter(Boolean))]
        this.departments = [...new Set(this.students.map(s => s.department).filter(Boolean))]
        this.filteredStudents = [...this.students]
      } catch (e) {
        this.$message.error('加载学生信息失败')
        console.error(e)
      }
    },
    filterData() {
      this.filteredStudents = this.students.filter(s => {
        return (!this.filters.college || s.college === this.filters.college) &&
               (!this.filters.department || s.department === this.filters.department) &&
               (!this.filters.grade || String(s.gradeYear) === String(this.filters.grade)) &&
               (!this.searchStudentId || String(s.studentId).includes(this.searchStudentId))
      })
    },
    deleteStudent(row) {
      this.$confirm(`确定删除学号为 ${row.studentId} 的学生吗？`, '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => axios.delete(`/api/students/${row.studentId}`)).then(() => {
        this.$message.success('删除成功')
        this.loadStudentData()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    openModule(key) {
      if (!this.selectedStudent) {
        this.$message.warning('请先选择一个学生')
        return
      }
      
      const mod = this.modules.find(m => m.key === key)
      if (mod) {
        this.currentModule = mod
        this.currentStudent = this.selectedStudent
      }
    },
    closeCurrentModule() {
      this.currentStudent = null
      this.currentModule = null
    },
    handleSaveSuccess() {
      this.$message.success('操作成功')
      this.loadStudentData()
    },
    handleStudentSelect(row) {
      this.selectedStudent = row
     
      if (this.currentModule) {
        this.currentStudent = row
        this.componentKey++
      }
    }
  }
}
</script>

<style scoped>
.admin-bg {
  height: 100vh;
  width: 100vw;
  background-image: url('@/assets/picture/5.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  overflow: auto;
}
.admin-container {
  width: 100%;
  padding: 0;
}
.nav-container {
  width: 95%;
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.app-header {
  background-color: #1e3a8a;
  color: white;
  padding: 15px 0;
  position: sticky;
  top: 0;
  z-index: 100;
}
.logo-title {
  display: flex;
  align-items: center;
  gap: 15px;
}
.logo {
  height: 50px;
}
.system-title {
  font-size: 24px;
  font-weight: bold;
}
nav ul {
  display: flex;
  list-style: none;
  gap: 25px;
  margin: 0;
  padding: 0;
}
nav a {
  color: white;
  text-decoration: none;
  font-size: 16px;
  padding: 5px 0;
}
nav a:hover {
  color: #93c5fd;
}
.main-area {
  max-width: 1200px;
  margin: 30px auto;
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 10px;
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08);
}
.page-title {
  font-size: 22px;
  margin-bottom: 20px;
  color: #1e3a8a;
  text-align: center;
}
.filter-row {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
}
</style>
